/* $Id: popup.jquery.js 22 2009-07-09 10:08:21Z geraldb $

Unobtrusive Accessible jQuery Pop Ups.

Overview:
	- Simulating target=_blank
	- Switching href (with no popups)
	- Attaching pop up actions to non-anchor objects

Usage:
	In your JavaScript use the syntax $('.popUpName').pop('windowName');
	or
	$('.popUpName').popup({
		target: '_blank',
		href: '/myPage', // Use this for a new href or if the object has no href property
		params: 'scrollbars=yes,resizable=yes,height=320,width=500',
		query: 'popup=true'
	});

Author:
	gburns

TODO:
	documentation
*/

(function($) {
$.fn.popup = function(settings) {
	if ( typeof(settings) == 'string' ) settings = { target: settings };

	settings = $.extend({
		target: '_blank',
		href: null,
		params: '',
		query: ''
	}, settings || {});

	return this.each(function() {
		var href, a, whandle;

		if ( settings.href ) {
			href = settings.href;
		} else if ( this.href ) {
			href = this.href;
		} else if ( (a = $('a', this)[0]) ) {
			href = a.href
		}

		if ( settings.query ) {
			// Replace query string
			if ( settings.query.indexOf('?') != -1 ) {
				href = href.replace(/[\?].*/, '') + settings.query;
			// Append query
			} else if ( href.indexOf('?') != -1 ) {
				href += '&' + settings.query;
			// Add query string
			} else if ( href.indexOf('#') != -1 ) {
				href = href.substring(0, href.indexOf('#')) + '?' + settings.query + href.substring(href.indexOf('#'));
			// Add query string
			} else {
				href += '?' + settings.query;
			}
		}

		if ( href ) {
			$(this).click(function(target, params, href) {
				return function() {
					$.popup.open(href, target, params);
					return false;
				}
			}(settings.target, settings.params, href));
		}
	});
}

$.popup = {
	windows: [],
	open: function(href, target, params) {
		var whandle;
		if ( params ) {
			whandle = window.open(href, target, params);
		} else {
			whandle = window.open(href, target);
		}
		if ( whandle ) $.popup.windows.push(whandle);
	},
	close: function() {
		if ( $.popup.windows.length ) {
			var w = $.popup.windows.pop();
			if ( w.close ) w.close();
		}
	},
	closeAll: function() {
		$($.popup.windows).each(function() {
			if ( this.close ) this.close();
		});
	}
}
})(jQuery);